import { defineStore } from 'pinia'
import {
  accountLoginRequest,
  getUserInfoById,
  getUserMenuByRoleId
} from '@/service/login/login'
import type { IAccount } from '@/types/index'
import { localCache } from '@/utils/cache'
import { mapMenusToRoutes } from '@/utils/map-menus'
import router from '@/router'
import { LOGIN_TOKEN } from '@/global/constants'
import { useEntriesDataStore } from '../main/main'

// 指定state的类型
interface IState {
  token: string
  userInfo: any
  userMenu: any
}
const useLoginStore = defineStore('login', {
  state: (): IState => ({
    token: '',
    userInfo: {},
    userMenu: []
  }),
  actions: {
    async loginAccountAction(account: IAccount) {
      const resLogin = await accountLoginRequest(account)
      const id = resLogin.data.id
      this.token = resLogin.data.token
      // 本地缓存
      localCache.setCache(LOGIN_TOKEN, this.token)
      // 获取登录用户的详情信息（role信息）
      const userInfoResult = await getUserInfoById(id)
      const userInfo = userInfoResult.data
      this.userInfo = userInfo

      // 根据用户的角色id请求用户的菜单权限（菜单menu）
      const userMenuResult = await getUserMenuByRoleId(this.userInfo.role.id)
      const userMenu = userMenuResult.data
      this.userMenu = userMenu
      // 将角色 菜单存储
      localCache.setCache('userInfo', userInfo)
      localCache.setCache('userMenu', userMenu)
      // console.log(userMenuResult)
      // 获取角色和部门列表
      const useRoleAndDepart = useEntriesDataStore()
      useRoleAndDepart.getEntriesDataAction()
      // 动态路由添加
      const routes = mapMenusToRoutes(userMenu)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
      // 登录成功后跳转到main
      if (this.token) {
        router.push('/main')
      }
    },
    loadLocalCacheAction() {
      const token = localCache.getCache(LOGIN_TOKEN)
      const userInfo = localCache.getCache('userInfo')
      const userMenu = localCache.getCache('userMenu')

      if (token && userInfo && userMenu) {
        this.token = token
        this.userInfo = userInfo
        this.userMenu = userMenu
        // 请求最新的角色和部门列表
        const useRoleAndDepart = useEntriesDataStore()
        useRoleAndDepart.getEntriesDataAction()
        // 动态路由添加
        const routes = mapMenusToRoutes(userMenu)
        routes.forEach((route) => {
          router.addRoute('main', route)
        })
      }
    }
  }
})

export default useLoginStore
